import java.io.*;
import java.util.HashMap;
import java.util.Map;

/*
  数据持久操作
 */
public class DataDao {

    // 数据用户存储的位置
    private static final  String FILEPATH = "src\\data.txt";

    static Map<String,Customer> map=new HashMap<>();



    static{
        File file = new File(FILEPATH);
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //反序列化
        try {
            ObjectInputStream objectInputStream
                    = new ObjectInputStream(new FileInputStream(FILEPATH));
            map = (Map<String,Customer>)objectInputStream.readObject();



        }catch (EOFException e){
            map=new HashMap<>();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    /*
     添加数据
     */

    public boolean addCustomer(Customer customer)  {
        map.put(customer.getId(),customer);
        return true;
    }

    /*
     判断编号是否存在
     */
    public boolean exitCustomerById(String id){
        return map.containsKey(id);
    }


    /*
     删除数据
     */
    public boolean deleteCustomerById(String id){
        map.remove(id);
        return true;
    }

    /*
     批量删除数据
     */
    /*public boolean batchDeleteById(String[] ids){
        for (String i:ids) {
            map.remove(i);
        }
        return true;
    }*/

    /*
    修改客户
     */
    public boolean updateCustomer(Customer customer){
        //根据客户的编号，修改客户的其他信息
        //先根据编号获取Map中客户
        Customer cx = map.get(customer.getId());
        cx.setName(customer.getName());
        cx.setBirthday(customer.getBirthday());
        cx.setGender(customer.getGender());
        return true;
    }

    /*
     获取所有雇员列表
     */
    public Map<String,Customer> obtainList(){
        return map;
    }

    /*
     序列化修改后的信息
     */
    public void update() throws IOException {
        //序列化
        ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(FILEPATH));
        stream.writeObject(map);

    }
}
